<?php
/**
 * Created by PhpStorm.
 * User: rain
 * Date: 2018/4/5
 * Time: 下午4:51
 */

namespace App\Http\Controllers\Api;


use App\Models\Book;
use App\Models\BookChapter;
use App\Models\BookWord;
use App\Models\UserBookChapter;
use App\Models\UserChapterWord;
use App\Services\UserService;
use App\User;
use App\Utils\ArrayUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class BookController extends AuthorizedController
{
    private $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }


    public function progress(Request $request)
    {
        $book = null;
        /** @var UserBookChapter $userBookChapter */
        $userBookChapter = UserBookChapter::where([
            'user_id' => $request->apiUser->id,
        ])->orderBy('updated_at', 'desc')->first();
        if (!empty($userBookChapter)){
            $book = $userBookChapter->book()->select(Book::$showFields)->first();

            $book->study_count = UserBookChapter::where([
                'user_id' => $request->apiUser->id,
                'book_id' => $book->id
            ])->sum('cor_word_ct');
        }


        return $this->success(['book' => $book]);
    }


    public function turn(Request $request)
    {
        $rules = [
            'book_chapter_id' => 'required|integer',
            'turn' => 'required|integer',
            'level' => 'required|integer',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()){
            return $this->success();
        }

        /** @var UserBookChapter $userBookChapter */
        $userBookChapter = UserBookChapter::where([
            'user_id' => $request->apiUser->id,
            'book_chapter_id' => $request->book_chapter_id
        ])->first();
        if (!empty($userBookChapter)){
            $userBookChapter->turn = $request->turn;
            $userBookChapter->level = $request->level;
            $userBookChapter->save();
        }


        return $this->success();
    }

    /**
     * 单词学习提交
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function word(Request $request)
    {
        $rules = [
            'book_word_id' => 'required|integer',
            'select_opt' => 'required|string',
            'is_right' => 'required|integer|in:0,1',
            'level' => 'required|integer|in:0,1,2,3',
            'remind' => 'required|integer|in:0,1,2',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()){
            return $this->error('参数错误');
        }

        /** @var BookWord $bookWord */
        $bookWord = BookWord::find($request->book_word_id);
        if (empty($bookWord)){
            return $this->error('章节单词不存在');
        }

        $isRight = $request->get('is_right', 0);
        $preStatus = $request->get('pre_status', 0);

        $userChapterWord = UserChapterWord::create([
            'user_id' => $request->apiUser->id,
            'book_id' => $bookWord->book_id,
            'book_chapter_id' => $bookWord->book_chapter_id,
            'book_word_id' => $bookWord->id,
            'select_opt' => $request->select_opt,
            'is_right' => $isRight,
            'level' => $request->get('is_right', 0),
            'remind' => $request->get('remind', 0),
            'date' => date('Y-m-d'),
            'pre_status' => $preStatus
        ]);

        //更新章节正确错误单词数
        $wordCt = UserChapterWord::where([
            'user_id' => $request->apiUser->id,
            'book_id' => $bookWord->book_id,
            'book_chapter_id' => $bookWord->book_chapter_id,
            'is_right' => $isRight,
        ])->groupBy('book_word_id')->select('book_word_id')->get()->toArray();
        $updateArr = ['cor_word_ct' => count($wordCt)];
        if ($isRight == false){
            //答错时，累计章节错误单词数
            $updateArr = ['error_cn_audio' => count($wordCt)];
        }

        /** @var UserBookChapter $userBookChapter */
        $userBookChapter = UserBookChapter::firstOrCreate([
            'user_id' => $request->apiUser->id,
            'book_id' => $bookWord->book_id,
            'book_chapter_id' => $bookWord->book_chapter_id,
        ]);
        $userBookChapter->fill($updateArr);
        $userBookChapter->updated_at = now();
        $userBookChapter->save();

        return $this->success(['user_chapter_word' => $userChapterWord]);
    }


    /**
     * 章节详情
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function chapter(Request $request)
    {
        $rules = [
            'book_chapter_id' => 'required|integer',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()){
            return $this->success();
        }

        /** @var BookChapter $bookChapter */
        $bookChapter = BookChapter::with([
            'words',
            'book' => function ($query){
                $query->select(Book::$showFields);
            }
        ])->find($request->book_chapter_id);
        if (empty($bookChapter)){
            return $this->success('章节不存在');
        }
        $bookChapter->turn = 0;
        $bookChapter->level = 0;

        $user = $this->getApiUser($request);

        if (!empty($user) && !empty($bookChapter)){

            $userBookChapter = UserBookChapter::where([
                'user_id' => $user->id,
                'book_id' => $bookChapter->book_id,
                'book_chapter_id' => $bookChapter->id,
            ])->first();

            if (!empty($userBookChapter)){
                $bookChapter->turn = (int)$userBookChapter->turn;
                $bookChapter->level = (int)$userBookChapter->level;
            }

        }

        return $this->success(['book_chapter' => $bookChapter]);
    }


    /**
     * 书籍章节列表
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function detail(Request $request)
    {
        $rules = [
            'book_id' => 'required|integer',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()){
            return $this->success();
        }
        $book = Book::with([
            'chapters' => function ($query){
                $query->select(['id', 'book_id', 'name', 'word_ct'])->orderBy('sort', 'asc');
            }
        ])->select(Book::$showFields)->find($request->book_id);
        if (empty($book)){
            return $this->success('书本不存在');
        }

        $userId = 0;
        $user = $this->getApiUser($request);

        if (!empty($user)){
            $userId = $user->id;
        }

        if (!empty($book)){
            $chapters = $book->chapters;
            $userBookChapters = UserBookChapter::where([
                'user_id' => $userId,
                'book_id' => $book->id
            ])->select(['cor_word_ct', 'book_chapter_id', 'turn', 'level'])->get()->toArray();
            $userBookChapters = ArrayUtil::index($userBookChapters, 'book_chapter_id');
            foreach($chapters as &$chapter){
                $chapter['cor_word_ct'] = 0;
                $chapter['turn'] = 0;
                $chapter['level'] = 0;
                if (isset($userBookChapters[$chapter['id']])){
                    $chapter['cor_word_ct'] = $userBookChapters[$chapter['id']]['cor_word_ct'];
                    $chapter['turn'] = (int)$userBookChapters[$chapter['id']]['turn'];
                    $chapter['level'] = (int)$userBookChapters[$chapter['id']]['level'];
                }
            }
            $book->chapters = $chapters;
        }

        return $this->success(['book' => $book]);
    }


    /**
     * 开始章节学习
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function startChapter(Request $request)
    {
        return $this->success();

        //        $rules = [
        //            'book_id' => 'required|integer',
        //            'book_chapter_id' => 'required|integer',
        //        ];
        //
        //        $validator = Validator::make($request->all(), $rules);
        //        if ($validator->fails()){
        //            return $this->success();
        //        }
        //
        //        $chapter = BookChapter::where(['id' => $request->book_chapter_id, 'book_id' => $request->book_id])->first();
        //        if (!empty($chapter)){
        //            UserBookChapter::firstOrCreate([
        //                'user_id' => $request->apiUser->id,
        //                'book_id' => $request->book_id,
        //                'book_chapter_id' => $request->book_chapter_id,
        //            ]);
        //        }
        //
        //        return $this->success();
    }


}
